<template>
  <div>
    <!--侧边栏组件开始-->
    <aside id="sidebar-wrapper" class="custom-scrollbar offcanvas-sidebar">
      <button class="off-canvas-close" @click="closeSideBar">
        <div class="">
        <i class="elegant-icon icon_close pr-10px"></i>
        </div>
      </button>
      <div class="sidebar-inner">
        <!--个人信息开始-->
        <div class="sidebar-widget widget_categories mb-50 mt-30" >
          <el-card class="box-card position-relative">
            <div slot="header" class="clearfix">
                <span>个人信息</span>
            </div>
            <div class="d-flex justify-content-center hover-up-2 transition-normal">
              <el-avatar class="author-avatar" :size="70" :src="userInfo.avatar"></el-avatar>
            </div>
            <el-divider></el-divider>
            <div>
              <ul>
                <li class="cat-item cat-item-2">
                  <a class="float-left">用户名:</a>
                  <span class="float-right">{{ userInfo.nickname }}</span>
                </li>
                <li class="cat-item cat-item-3">
                  <a class="float-left">邮箱：</a>
                  <span class="float-right">{{ userInfo.username }}</span>
                </li>
                <li class="cat-item cat-item-4">
                  <a class="float-left">登录类型：</a>
                  <span class="float-right">{{ userInfo.loginType }}</span>
                </li>
                <li class="cat-item cat-item-5">
                  <a class="float-left">网站：</a>
                  <span class="float-right">{{ userInfo.webSite }}</span>
                </li>
                <li class="cat-item cat-item-6">
                  <a class="float-left">个人简介：</a>
                  <span class="float-right">{{ userInfo.intro }}</span>
                </li>
              </ul>
            </div>
            <el-divider></el-divider>
            <div class="float-right pb-10">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showDailog"
              >修改个人信息</el-button>
            </div>
            <div class="float-left pb-10">
              <el-button
                type="warning"
                icon="el-icon-arrow-right"
                size="mini"
                @click="closeSideBar"
              ></el-button>
            </div>
          </el-card>
        </div>
        <!-- 跟人信息结束 -->
        <!--修改密码开始-->
        <div class="sidebar-widget widget-latest-posts mb-50">
            <el-card class="box-card position-relative">
            <div slot="header" class="clearfix">
                <span>修改密码</span>
            </div>
            <el-form label-width="70px" label-position="left" ref="rulePassword"
            :model="passwordForm"
            :rules="rulesPassword">
            <el-form-item label="邮箱">
            <el-input
              placeholder=""
              disabled
              v-model="passwordForm.username"
            ></el-input>
            </el-form-item> 
            <el-form-item label="验证码" prop="code">
            <el-input
            v-model="passwordForm.code"
              placeholder="验证码"
            ></el-input>
          
            </el-form-item>
            <el-form-item label="密码" prop="password">
            <el-input
            v-model="passwordForm.password"
              placeholder="请输入密码"
              label-width="0"
              type="password"
            ></el-input>
            </el-form-item>
                <el-form-item label="密码" prop="repassword">
            <el-input
            v-model="passwordForm.repassword"
              type="password"
              placeholder="请输入密码"
            ></el-input>
            </el-form-item>
            </el-form>
            <div class="float-right pb-10">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="updateUserPassword"
              >修改</el-button>
            </div>
            <div class="float-left pb-10">
              <el-button
                type="warning"
                icon="el-icon-arrow-right"
                size="mini"
                @click="closeSideBar"
              ></el-button>
            </div>
                  <div class="text-center pb-10">
              <el-button
                type="pramiry"
                icon="el-icon-message"
                size="mini"
                @click="getCode"
                :disabled="countingDown"
              >{{codeName}}</el-button>
            </div>
            </el-card>
        </div>
        <el-button size="mini" type="danger" @click="logout" class="float-right">退出登录</el-button>
      </div>
      <!-- 对话框 -->
    </aside>
    <!-- 侧边栏组件结束 -->
    <div class="col-md-12">
      <!-- 对话框 -->
      <el-dialog
        title="修改个人信息"
        :visible.sync="dialogVisible"
        :width="dialogWidth"
      >
        <el-form
          ref="ruleForm"
          :model="user"
          :rules="rules"
          label-width="70px"
          label-position="left"
        >
          <el-form-item label="头像" prop="logoUrl">
            <!-- action图片上传地址
            :on-success="handleAvatarSuccess" 当图片上传成功执行
            :before-upload="beforeAvatarUpload" 上传之前的回调
           -->
            <!-- 上传图片不能使用v-model因为不是表单元素 
           action：设置图片上传的地址
                 
            :show-file-list="false"
           
            :before-upload="beforeAvatarUpload"
           -->
            <el-upload  
              action="/api/user/updateAvatar"
             :on-success="handleAvatarSuccess"
             :before-upload="beforeAvatarUpload"
             :headers="headers"
             ref="upload"
             class="avatar-uploader">
              <img
                v-if="user.avatar"
                :src="user.avatar"
                class="avatar"
                style="width: 100px"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"> </i>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="账号">
            <el-input
              placeholder=""
              :disabled="true"
              v-model="user.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input
              placeholder="请输入昵称"
              v-model="user.nickname"
            ></el-input>
          </el-form-item>
          <el-form-item label="自我介绍">
            <el-input
              placeholder="请输入自我介绍"
              v-model="user.intro"
            ></el-input>
          </el-form-item>
          <el-form-item label="个人网站">
            <el-input
              placeholder="请输入链接"
              v-model="user.webSite"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateUserInfo"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getToken } from "@/utils/token";
export default {
  name: "MySideBar",
  data() {
    return {
      dialogVisible: false,
      dialogWidth: "50%",
      user: {
        username: "",
        webSite: "",
        intro: "",
        nickname: "",
        avatar: "",
      },

      //用户信息表单验证规则
      rules: {
        nickname: [
          // required:必须要填写的字段（前面的五角星相关） Message 提示信息 trigger 用户行为设置（blur（失去焦点）、change（变化））
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "change",
          },
        ],
      },
    passwordForm:{
            username:"",
            code:"",
            password:"",
            repassword:""
        },
      //密码验证规则
      rulesPassword:{
            code: [
      { required: true, message: "请输入验证码", trigger: "blur" },
      {
        pattern: /^[0-9]{6}$/,
        message: "验证码必须为6位数字",
        trigger: "blur",
      },
    ],
    password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
   repassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== this.passwordForm.repassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
      },
      totalTime: 60, // 初始倒计时秒数
      countingDown: false, // 是否正在倒计时
      codeName:'验证码'
    };
  },
    computed: {
    ...mapState("user", ["userInfo"]), // 将 Vuex 中的状态映射到组件的计算属性中
    //校验密码
    passwordMatch() {
    return this.passwordForm.password === this.passwordForm.repassword;
    },
    //上传头像请求需要携带token
    headers(){
      const token = getToken()
      return {token}
    }
  },
  created(){
    this.passwordForm.username=this.userInfo.username;
  },
  mounted() {
   this.setDialogWidth();
  },
  watch:{

  },
  methods: {
    // 开启侧边栏
    openSideBar() {
      const bodyElement = document.querySelector("body");
      bodyElement.className = "canvas-opened";
    },
    //关闭侧边栏
    closeSideBar() {
      const bodyElement = document.querySelector("body");
      bodyElement.className = "";
    },
    //显示对话框
    showDailog() {
      this.user.username = this.userInfo.username;
      this.user.webSite = this.userInfo.webSite;
      this.user.intro = this.userInfo.intro;
      this.user.nickname = this.userInfo.nickname;
      this.user.avatar = this.userInfo.avatar;
      this.dialogVisible = true;
    },

    //对话框大小
    setDialogWidth() {
      console.log(document.body.clientWidth);
      var val = document.body.clientWidth;
      const def = 800; // 默认宽度
      if (val < def) {
        this.dialogWidth = "100%";
        console.log('100%')
      } else {
        this.dialogWidth = "50%";
        console.log('50%')
      }
    },
    //修改信息
    async updateUserInfo() {
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          let res = await this.$API.user.updateUser(this.user);
          if (res.code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            //重新获取用户信息
            this.$store.dispatch("user/getUserInfo");
            this.user = { username: "", webSite: "",intro: "",nickname: "",avatar: "",}
            this.dialogVisible = false;
          } else {
            this.$message(
              {
                message: res.msg,
                type: "error",
              },
            )
          }
        } else {
          return false;
        }
      });
    },
    //头像上传成功的回调
    handleAvatarSuccess(response, file){
        this.$refs.upload.clearFiles();
        this.$message({
          message: "上传成功",
          type: "success",
        });
        console.log(response)
        this.user.avatar = response.data
    },
    //头像之前的回调
    beforeAvatarUpload(){
    },
    //获取验证码
    async getCode(){
        let res = await this.$API.user.getPwdCode(this.passwordForm.username);
        if(res.code == 200)
        {
            this.$message({
              message: "验证码发送成功",
              type: "success",
            });
            this.updatetotalTime();
        }
        else{
            this.$message({
              message: res.msg,
              type: "error",
            });
        }
    },
    //修改密码
    updateUserPassword(){
        this.$refs.rulePassword.validate(async (success) => {
            if(success)
            {
                let res = await this.$API.user.updateUserPassword(this.passwordForm);
                if(res.code == 200)
                {
                    this.$message({
                      message: "修改成功",
                      type: "success",
                    });
                    //派发action
                    await this.$store.dispatch("user/resetToken");
                    this.$router.push('/login')
                }
                else{
                    this.$message({
                      type:'error',
                      message: res.msg,
                    })
                }
            }
            else{
                return false;      
            }
        })
    },
    //退出登录
    async logout() {
         this.$confirm('是否确定退出登录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
             try {
        await this.$store.dispatch("user/logout"); // 调用退出登录的 Vuex action
        this.$router.push("/"); // 退出成功后重定向到首页
        this.$message({
            message: "退出成功",
            type: "success",
        })
      } catch (error) {
        this.$message({
            message: error,
            type: "warning",
        })
      }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });

    },
    //验证码倒计时 
    updatetotalTime() {
      if (this.totalTime > 0) {
        this.countingDown = true;
        setTimeout(() => {
          this.totalTime -= 1;
          this.codeName = this.totalTime + 's'
          this.updatetotalTime();
        }, 1000);
      } else {
        this.countingDown = false;
        this.totalTime = 60; // 重置倒计时
        this.codeName = '验证码'
      }
    },

  },
  beforeDestroy() {
    this.closeSideBar();
  },

};
</script>

<style>
.author-avatar {
  width: 100px;
  height: 100px;
  transform-origin: center;
  filter: blur(0); /* 初始状态为清晰效果 */
  transition: transform 0.5s ease, filter 0.5s ease; /* 添加 transform 和 filter 属性的过渡效果 */
}

.author-avatar:hover {
  transform: scale(1.2) rotate(360deg); /* 鼠标移入时放大并旋转一圈 */
  filter: blur(0); /* 悬停时立即清晰 */
}

.author-avatar:not(:hover) {
  filter: blur(10px); /* 鼠标移出时立即模糊 */
  animation: clearBlur 0.5s 0.5s forwards; /* 模糊立即生效，然后0.5秒后逐渐清晰 */
}

@keyframes clearBlur {
  to {
    filter: blur(0); /* 0.5秒后逐渐清晰 */
  }
}
</style>